package com.gh.controller.api;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.gh.common.result.R;
import com.gh.common.util.MD5;
import com.gh.hfb.RequestHelper;
import com.gh.service.UserBindService;
import com.gh.utils.JwtUtils;
import com.gh.vo.UserBindVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 用户绑定表 前端控制器
 * </p>
 *
 * @author Eric
 * @since 2021-09-06
 */
@Api(tags = "会员账号绑定")
@RestController
@RequestMapping("/api/core/userBind")
@Slf4j
public class UserBindController {

    @Resource
    private UserBindService userBindService;

    @ApiOperation("账户绑定提交数据")
    @PostMapping("/auth/bind")
    public R bind(@RequestBody UserBindVo userBindVo, HttpServletRequest request) {
        //从header中拿到token进行效验，确保用户已登录，从token获取userId
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        //根据userId做账户绑定,生成一个动态表单的字符串
        String formStr = userBindService.commitUserBind(userBindVo, userId);
        return R.ok().data("formStr", formStr);
    }

    @ApiOperation("账户绑定异步回调")
    @PostMapping("/notify")
    public String notifyBind(HttpServletRequest request) {
        //汇付宝向尚融宝发送请求时携带的参数
        Map<String, Object> map = RequestHelper.switchMap(request.getParameterMap());
        log.info("账户绑定异步回调参数如下：{}", JSON.toJSONString(map));
        //校验签名
        boolean signEquals = RequestHelper.isSignEquals(map);
        if(!signEquals){
            log.error("用户账户异步绑定回调签名错误");
            return "fail";//随便都可以
        }
        log.info("验签成功，开始绑定");
        userBindService.notifyBind(map);
        return "success";
    }
}

